package com.zz.bsea.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;

import java.util.List;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class FileUploadDemo1Servlet
 */
public class FileUploadDemo1Servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileUploadDemo1Servlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		DiskFileItemFactory factory = new DiskFileItemFactory(); 
		 //当内存中文件数据达到THRESHOLD_SIZE后，就写入临时文件中，避免上传大文件时，消化太多内存 
	    ServletFileUpload upload = new ServletFileUpload(factory); 
	    upload.setHeaderEncoding("UTF-8"); 
	    upload.setSizeMax(2*1024*1024); 
	    //上传以后，文件保存的地址  / \
	    String savePath="D:\\bsea\\wp\\java11\\src\\main\\webapp\\files";
	    try {
	    	// 获取 from表单里面，所有的元素
			List items = upload.parseRequest(request);
			
			//form 循环 遍历表单里面的元素集合
			for(int i=0;i<items.size();i++){
				//每个表单元素，都封装到一个FileItem类型的对象中
				FileItem fitem=(FileItem) items.get(i);
				System.out.println("元素name属性的值是="+fitem.getFieldName());
				
				//  fitem.isFormField() 表示，如果当前这个元素的类型type不等于file,那么就返回true
				if(fitem.isFormField() ){
					System.out.println("这是一个普通的非文件字段");
					System.out.println("输入框，前端输入的值是---"+fitem.getString());
					
				}else{
					
					System.out.println("这是一个文件字段");
					System.out.println("fitem.getName() 原始的文件名字--"+fitem.getName());
					//File.separator 这是一个静态的变量。 
					// 在windows的操作系统返回值是 \\  如果是linux系统，返回是一个  /
					
					
					//设置文件的名字
					String orgFileName=fitem.getName();
					//因为浏览器不同，IE会获取到“\” 但是谷歌浏览器只有文件名字
					if(orgFileName.indexOf("\\")!=-1) {
						orgFileName=orgFileName.substring(orgFileName.lastIndexOf("\\")+1);
					}
					String filename=System.currentTimeMillis()+"-"+orgFileName;
					System.out.println("filename===="+filename);
					
					//存储上传的文件
					String finalFileName=savePath+File.separator+filename;
					System.out.println("finalFileName===="+finalFileName);
					File file=new File(finalFileName);
					try {
						fitem.write(file);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
